<template>
  <edit-dialog
    :centerDialogVisible="visible"
    :tilte="tilte"
    :default-button="false"
    @Cancel="handleCancel"
    :width="width"
  >
    <template #content>
      <div style="height: 200px;overflow-y: auto;overflow-x: hidden;">
        <el-form
          ref="addGoodsFormRef"
          :model="addForm"
          :rules="rules"
          label-position="right"
          label-width="125px"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item label="文件名称：" prop="enclosureName">
            <el-input
              v-model.trim="addForm.enclosureName"
              placeholder="请输入文件名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="文件编号：" prop="goodsType">
            <el-input
              v-model.trim="addForm.code"
              disabled
            />
          </el-form-item>
          <el-form-item label="文件版本：" prop="timeLimit">
            <el-input v-model="addForm.enclosureVersion" disabled >
            </el-input>
          </el-form-item>
          <el-form-item label="文件大小：" prop="lostName">
            <el-input
              v-model.trim="addForm.enclosureSize"
              disabled
            />
          </el-form-item>
          <el-form-item label="文件格式：" prop="lostPhone">
            <el-input
              maxlength="15"
              v-model.trim="addForm.enclosureType"
              disabled
            />
          </el-form-item>
          <el-form-item label="文件上传：">
            <el-upload  style="width: 100%"
                        ref="elUploadFile"    :on-change="handleChangeFile" action="#" :on-exceed="handleExceed"  :limit="1" :auto-upload="false">
              <!-- <el-button type="primary">Click to upload</el-button> -->
              <button>选择文件</button>&nbsp;&nbsp;
              <template #tip>
                <span>{{addForm.enclosureName?addForm.enclosureName+'.'+addForm.enclosureType:'未选择任何文件'}}</span>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button
          class="btn-ok"
          @click="handleAddSubmit(addGoodsFormRef)"
        >确定</el-button>

      </span>
    </template>
  </edit-dialog>

</template>

<script lang="ts" setup>
  import { ref, reactive, defineProps, computed, watch } from "vue";
  import { useStore } from "vuex";
  import editDialog from "@/components/editDialog/index.vue";
  import {ElMessage, FormInstance, FormRules, genFileId, UploadProps, UploadRawFile} from "element-plus";
  import {uploadFiles, uploadKonwledgeFiles} from "@/api/common";
  import {UpdateFiles} from "@/api/knowledge/enclosure";
  const addGoodsFormRef = ref<FormInstance>();

  const tilte = ref("修改");
  const width = ref("775px");
  const store = useStore();
  const disabled = ref(false);
  const userInfo = computed(() => store.state.user.userInfo);
  const addForm = ref({
    enclosureName: '', // 文件前缀 TCDM
    enclosureType: '', // 文件后缀md
    path: '', // 文件相对地址，网关地址+resourceAddres即可完成下载
    enclosureCode: '', // 唯一标识
    directoryCode: '',
    enclosureSize: '',
    enclosureClassification: 1,
    enclosureVersion:'',
    code:'',
    id:0,
    lastMender: {
      id: "",
      name: "",
      userName:"",
      organId: '',
      organName: ''
    }
  });


  const rules = reactive<FormRules>({
    enclosureName: [
      { required: true, message: "请输入文件名称", trigger: "blur" },
      { max: 50, message: "最大长度50", trigger: "blur" },
    ],
  });

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    goodsType: {
      type: Array,
    },
    info: {
      type: Object,
    },
  });

  const fileList = ref();

  const dialogImageUrl = ref("");
  const dialogVisible = ref(false);
  const emit = defineEmits(["cancel", "ok"]);


  const handleChangeFile: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    console.log('uploadFile',uploadFile)
    console.log('uploadFiles',uploadFiles)

    fileList.value = uploadFile
    getFile(uploadFile)
  }
  const elUploadFile = ref();
  const handleExceed: UploadProps['onExceed'] = (files) => {
    elUploadFile.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    elUploadFile.value!.handleStart(file)
  }
  const getFile= async (ele: any) => {
    const fileName = ele.name;
    const isSyncEs = 'true';
    const enclosureSize = ele.size
    const index = fileName.lastIndexOf('.')
    const name = fileName.slice(0, index)
    let formData = new FormData();
    formData.append('file', ele.raw)
    formData.append('fileName', name)
    formData.append('isSyncEs',isSyncEs);
    let res = null;
    try {
      res = await uploadKonwledgeFiles(formData)
    } catch {
      ElMessage.error(`${name}上传失败`)
    }
    if (res?.data) {
      addForm.value.enclosureName=res.data.enclosureName
      addForm.value.enclosureType=res.data.enclosureSuffix
      addForm.value.path=res.data.resourceAddress
      addForm.value.enclosureCode=res.data.enclosureCode
      addForm.value.enclosureSize=(ele.size/1024).toFixed(2)+'KB'
    }
  }

  /**
   * 取消
   */
  const handleCancel = () => {
    emit("cancel");
  };


  /**
   * 提交
   */
  const handleAddSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
      return;
    }
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        const res=await UpdateFiles(addForm.value)
        if(res.code=='1'){
          ElMessage.success(`更新成功`)
          emit("ok")
        }else{
          ElMessage.error(`更新失败`)
        }
      }
    });
  };
  watch(
    () => props.visible,
    async (val) => {

        if (props.info) {
          const info = props.info;

            addForm.value={
              enclosureName: info.enclosureName, // 文件前缀 TCDM
              enclosureType:info.enclosureType, // 文件后缀md
              path: info.path, // 文件相对地址，网关地址+resourceAddres即可完成下载
              enclosureCode: info.enclosureCode, // 唯一标识
              directoryCode: info.directoryCode,
              enclosureSize: info.enclosureSize,
              enclosureClassification: info.enclosureClassification,
              enclosureVersion:info.enclosureVersion,
              code:info.code,
              id:info.id,
              lastMender: {
                id: userInfo.value.userId,
                name: userInfo.value.name,
                userName: userInfo.value.userName,
                organId: userInfo.value.organId || '',
                organName: userInfo.value.organName || ''
              }

          }
        }
    }
  );
</script>

<style lang="less" scoped>
  .hide {
    /deep/ .el-upload--picture-card {
      display: none;
    }
    /deep/ .el-list-enter-active,
    .el-list-leave-active {
      transition: all 0s;
    }
    /deep/ .el-list-enter,
    .el-list-leave-active {
      opacity: 0;
      transform: translateY(0);
    }
  }
  .upload-img {
    width: 100%;
  }
  /deep/.el-form-item__content {
    width: 200px;
  }
  .lost-time {
    /deep/.el-form-item__content {
      width: 350px;
    }
  }
  .buttonCancel {
    width: 80px;
    background: #fff;
  }
  .buttonCancel:hover {
    color: green;
    border-color: green;
    background: #fff;
  }
  .btn-ok {
    width: 80px;
    color: #337fcc;
    border: 1px solid #337fcc;
  }
  .btn-match {
    width: 80px;
    color: #fff;
    background: #337fcc;
    border-radius: 6px;
    border: 1px solid #337fcc;
  }
</style>
